<template>
  <render/>
</template>
<script setup>
import {createProps, getFieldConfigById} from '@/utils';
import Constants from '@comp/FormEngine/Constants';
import FieldDelegate from '@comp/FormEngine/FieldDelegate.vue';
import {h} from 'vue';
import FieldRegistry from '@comp/FormEngine/field/FieldRegistry';

defineOptions({name: 'FormComponentDelegate'});

const props = defineProps({
  config: createProps(Object, () => undefined),
  context: createProps(Object, () => undefined),
  forceDetail: createProps(Boolean),
  rowIndex: createProps(Number, undefined),
  formModel: createProps(Object, () => undefined),
  subFormId: createProps(String),
  rowId: createProps(String),
});

function render() {
  if (!props.config || !props.config || !props?.context?.formModel) return undefined;
  if (isField()) {
    return renderField();
  }
  if (isCard()) {
    return renderCard();
  }
  if (isLayout()) {
    return renderLayout();
  }
  if (isSubForm()) {
    return renderSubForm();
  }
}

function isSubForm() {
  return props?.config?.type === Constants.subTable
}

function renderSubForm() {
  return h(FieldRegistry.subTable, {
    config: props.config,
    context: props.context,
  });
}

function renderField() {
  let fieldId = props.config.fieldId;
  let fieldConfig = getFieldConfigById(fieldId, props.context.formDefinition);
  return h(FieldDelegate, {
    fieldConfig, context: props.context,
    formModel: props.formModel || props.context.formModel,
    showLabel: props.context?.showLabel() || false,
    rowIndex: props.rowIndex,
    rowId: props.rowId,
    subFormId: props.subFormId,
    forceDetail: props.forceDetail
  });
}

function renderLayout() {
  return h(FieldRegistry.layout, {
    context: props.context,
    config: props.config,
  });
}

function renderCard() {
  return h(FieldRegistry.card, {
    config: props.config,
    context: props.context,
  });
}

function isCard() {
  if (props?.config?.type === 'card') return true;
}

function isField() {
  return props.config && props.config.type === Constants.field;
}

function isLayout() {
  return props.config && props.config.type === Constants.layout && !props.config.subFormId;
}
</script>
<style scoped lang="scss">

</style>